package com.jsoft.controller;

import com.alibaba.fastjson.JSON;
import com.jsoft.entity.User;
import com.jsoft.service.UserService;
import com.jsoft.service.impl.UserServiceImpl;
import com.jsoft.utils.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 用户控制层
 * @author : yhx
 * @version : 1.0
 * @date : 2023/2/19
 */
@WebServlet("*.user")
public class UserController extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        // 1.获取servletPath /front/xxx.user
        String servletPath = req.getServletPath();
        // 2.获取到xxx
        String methodName = servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length() - 5);

        try {
            // 3.利用反射获取对应的方法对象
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 4.执行对应的方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();

        BufferedReader reader = req.getReader();
        String json = reader.readLine();
        User user = JSON.parseObject(json, User.class);
        boolean flag = false;
        try {
            int i = userService.loginUser(user.getAccount(), user.getPassword());
            if (i > 0) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            out.write(JSON.toJSONString(new ResultUtil("100", "1111")));
        } else {
            out.write(JSON.toJSONString(new ResultUtil("101", "2222")));
        }
        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
